package com.cheer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.dao.OaRuleDao;
import com.cheer.entity.OaRuleEntity;
import com.cheer.service.OaIntegralService;
import com.cheer.service.OaRuleService;
import com.cheer.service.OaUserService;
import com.cheer.vo.OaLevelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service("oaRuleService")
public class OaRuleServiceImpl extends ServiceImpl<OaRuleDao, OaRuleEntity> implements OaRuleService {

    @Value("${image.url}")
    private String imageUrl;

    @Autowired
    private OaUserService oaUserService;

    @Autowired
    private OaIntegralService oaIntegralService;

    private volatile List<OaRuleEntity> rulesCache;

    @Override
    public void loadRules() {
        List<OaRuleEntity> rules = list();

        rulesCache = rules.stream().peek(oaRuleEntity -> oaRuleEntity.setIconUrl(imageUrl + oaRuleEntity.getIconUrl()))
                .sorted(Comparator.comparingLong(OaRuleEntity::getLevel))
                .collect(Collectors.toList());
    }

    @Override
    public List<OaRuleEntity> listRules() {
        if (rulesCache != null) {
            return rulesCache;
        }
        loadRules();
        return rulesCache;
    }

    @Override
    public OaLevelVO getLevel(Integer userId, String openid) {
        if (rulesCache == null) {
            loadRules();
        }

        Integer yearPoints = oaIntegralService.getByYear(openid, userId);

        for (OaRuleEntity rule : rulesCache) {
            if (yearPoints <= rule.getPoint()) {
                continue;
            }

            return new OaLevelVO()
                    .setIsRanked(true)
                    .setUsername(oaUserService.getUsernameById(userId))
                    .setPoints(yearPoints)
                    .setHonorTitle(rule.getHonorTitle())
                    .setRank(rule.getRank())
                    .setIconUrl(rule.getIconUrl())
                    .setDescription(rule.getDescription());
        }

        return new OaLevelVO().setHonorTitle("未上榜").setIsRanked(false);
    }

}